import os
import sys

from PyQt6.QtCore import QThread, QObject, pyqtSignal, QStringListModel
from PyQt6.QtWidgets import QApplication, QMainWindow, QLineEdit, QListView, QPushButton, QWidget, QAbstractItemView
from PyQt6.uic import loadUi

import main_model
from global_config import workflows_dir, root
from midjourney_config import *
from scripts import db_utils
from ui.DrawPage import DrawPage
from ui.OriginPage import OriginPage
from ui.WashPage import WashPage
from ui.widgets.notice_dialog import ConfirmDialog


class Create_page(QWidget):
    def __init__(self, view):
        super().__init__()
        self.parent = view
        self.pushButton: QPushButton = None
        self.originButton: QPushButton = None
        self.draft_btn: QPushButton = None
        self.draft_edit: QLineEdit = None
        self.listView: QListView = None
        self.project_edit: QLineEdit = None
        self.initUI()

    def initUI(self):
        self.splashui = loadUi('./source/create_page.ui', self)

        self.pushButton.clicked.connect(
            lambda: self.create_project(self.project_edit.text(), type_wash)
        )
        self.originButton.clicked.connect(
            lambda: self.create_project(self.project_edit.text(), type_origin)
        )
        self.draft_btn.clicked.connect(self.save_jianyin_drafts)
        self.listView.doubleClicked.connect(self.on_double_click)

        model = QStringListModel((f"{v}" for v in os.listdir(workflows_dir)))
        self.listView.setModel(model)

        file = f'{root}\\setting_jianying_dir'
        if os.path.exists(file):
            with open(file, 'r') as file:
                self.draft_edit.setText(file.read())

    def create_project(self,name,  type):
        if name == '' or name is None:
            dialog = ConfirmDialog('提示', '请输入工程名称')
            result = dialog.get_result()
            return
        # 创建项目
        main_model.create_project(name, type)

        if type == type_origin:
            form_class = OriginPage()
        else:
            form_class = WashPage()

        self.parent.setCentralWidget(form_class)

    def on_double_click(self, index):
        item = self.listView.model().data(index)
        db_utils.set_cur_project(item)
        project = db_utils.load_project_config()
        self.create_project(item, project['type'])

    def save_jianyin_drafts(self):
        test = self.draft_edit.text()
        if test == '': return
        file = f'{root}\\setting_jianying_dir'
        with open(file, 'w') as file:
            file.write(test)
